<template>
    <div >
        <div  class="buttons">
            
            <button v-for="(item,index) of buttons" :key="index" 
            type="button" 
            class="el-button el-button--primary el-button--medium "
            :class="{active:isBtn==index}"
            @click="handleBtnClick(index)"
            >
                <span>{{item}}</span>
            </button>
        </div>
        <div id="cesiumContainer">
            <div  id="eq_detail" class="EquipmentDetails" style="display: none; position: absolute; ">
                <span @click="hiddenInfoBox" class="el-icon-close"></span>
                <ul >
                    <li v-for="(item,index) in infoList" :key = "index">{{item}}</li>
                </ul>
            </div>
            <div  id="pop_nenghao" class="EnergyConsumption" style="display: none; position: absolute; ">
                <span @click="hiddenPopBox" class="el-icon-close"></span>
                <div class="tabs-wrap">
                    <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
                        <el-tab-pane label="基本信息" name="first">
                            <ul >
                                <li v-for="(item,index) in nenghaoList" :key = "index">{{item}}</li>
                            </ul>
                        </el-tab-pane>
                        <el-tab-pane label="监测数据" name="second">
                            <el-table
                                :data="tableData"
                                height="250"
                                border
                                style="width: 100%">
                                <el-table-column
                                    prop="num"
                                    label="监测设备编号"
                                    width="180">
                                </el-table-column>
                                <el-table-column
                                    prop="time"
                                    label="监测时间"
                                    width="180">
                                </el-table-column>
                                <el-table-column
                                    prop="type"
                                    label="能耗类型">
                                </el-table-column>
                                <el-table-column
                                    prop="data"
                                    label="能耗数据">
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="统计图" name="third">
                            <div id="nenghaoChart" ref="nenghaoChart" >
                            </div>
                        </el-tab-pane>
                        
                    </el-tabs>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { mapState, mapGetters, mapMutations ,mapActions} from 'vuex'
import axios from 'axios'
export default {
    name:"CesiumContainer",
    data(){
        return {
            preRenderListener:null,
            infoList:[],
            nenghaoList:[],
            i: Date.now(),
            isBtn:-1,
            tableData: [],
            activeName: 'first',
            currentEntity:null,
            buttons:[
                "初始化数据","运行监测","能效统计","使用管理"
            ]
        }
    },
    computed:{
        ...mapState("windowInfo",{
            infoBoxContent:"infoBoxContent"
        }),
    },
    mounted(){
        this.$cp.cesiumInit();
        
        //this.getXy()
        var url = "http://citycim.g-bim.cn/sngdemo/static/3dtiles/%E5%8D%97%E4%BA%AC%E9%9D%92%E5%B0%91%E5%B9%B4%E5%AE%AB-%E5%BB%BA%E7%AD%91-F03/tileset.json";
        var url1 = "http://citycim.g-bim.cn/sngdemo/static/3dtiles/%E5%8D%97%E4%BA%AC%E9%9D%92%E5%B0%91%E5%B9%B4%E5%AE%AB-%E7%BB%93%E6%9E%84-F03/tileset.json";
        this.addTiles(url);
        this.addTiles(url1);
        //this.$cp.addPolygon()
        this.$cp.initCesiumView(118.76857488760477,32.07172775831959,130,0.6708941722301089,-0.9083850719785813,0.0030597702001138316)
        
       
    
    },
    methods:{
        handleTabClick(tab, event) {
           
            if(tab.name=="third"){
                let timeArr = [];
                let nenghaoArr = [];
                axios.get("./data/lonLat.json").then((res)=>{
                    let data = res.data.rows[0]["能耗监测"];
                    data.forEach(item=>{
                        if(item["监测设备编号"]===this.currentEntity["设备编号"]){
                            timeArr.push(item["监测时间"]);
                            nenghaoArr.push(item["能耗数据"]);
                        }
                    })
                    this.drawNenghao(timeArr,nenghaoArr)
                })
            }
            
        },
        handleBtnClick(index){
            this.isBtn = index
            if(index == 0){
                viewer.entities.removeAll();
                this.initDevice(deviceData)
            }else if(index==1){
                //运行监测
                //去掉11和18，添加新的11和18，11是烟雾，18是温度
                viewer.entities.removeAll();
                axios.get("./data/lonLat.json").then((res)=>{
                    let data = res.data.rows[0]["设备设施"];
                    this.initDevice(data);
                    viewer.entities.removeById('NJ_F03_YW_002');
                    viewer.entities.removeById('NJ_F03_WD_002');
                    let item1 = deviceData[10];
                    let item2 = deviceData[17];
                    this.$cp.addBillboardTwinkle('NJ_F03_YW_002',item1,[item1["lon"], item1["lat"], item1["height"]],yanwuBJ,'leftClick',this.handleLeftClick);
                    this.$cp.addBillboardTwinkle('NJ_F03_WD_002',item2,[item2["lon"], item2["lat"], item2["height"]],wenduBJ,'leftClick',this.handleLeftClick);

                })
                
            }else if(index==2){
                //能效统计
                viewer.entities.removeAll();
                this.$cp.addPolygon("redP",redArea,"#f00");
                this.$cp.addPolygon("greenPolgon",greenArea,"#ff0");
                let item1 = deviceData[5];
                let item2 = deviceData[6];
                let item3 = deviceData[7];
                let item4 = deviceData[8];
                this.$cp.addBillboard('NJ_F03_WB_001',item1,[item1["lon"], item1["lat"], item1["height"]],shuibiao,'leftClick',this.handleLeftClick);
                this.$cp.addBillboard('NJ_F03_WB_002',item2,[item2["lon"], item2["lat"], item2["height"]],shuibiao,'leftClick',this.handleLeftClick);
                this.$cp.addBillboard('NJ_F03_DB_001',item3,[item3["lon"], item3["lat"], item3["height"]],dianbiao,'leftClick',this.handleLeftClick);
                this.$cp.addBillboard('NJ_F03_DB_002',item4,[item4["lon"], item4["lat"], item4["height"]],dianbiao,'leftClick',this.handleLeftClick);
            }else if(index==3){
            //使用管理
                viewer.entities.removeAll();
                axios.get("./data/lonLat.json").then((res)=>{
                    let data = res.data.rows[0]["设备设施"];
                    this.initDevice(data);
                    viewer.entities.removeById('NJ_F03_YW_002');
                    viewer.entities.removeById('NJ_F03_WD_002');
                    let item1 = deviceData[10];
                    let item2 = deviceData[17];
                    this.$cp.addBillboardTwinkle('NJ_F03_YW_002',item1,[item1["lon"], item1["lat"], item1["height"]],yanwuBJ,'leftClick',this.handleLeftClick);
                    this.$cp.addBillboardTwinkle('NJ_F03_WD_002',item2,[item2["lon"], item2["lat"], item2["height"]],wenduBJ,'leftClick',this.handleLeftClick);
                })
            }
        },
        initDevice(arr){
            let that = this;
            arr.forEach((item)=>{
                switch(item["设备品牌"]) {
                case "海康":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"], item["lat"], item["height"]],jiankong,'leftClick',that.handleLeftClick);
                    that.$cp.addTiles(jiankongUrl , item["matrix"])
                    break;
                case "顺水":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],shuibiao,'leftClick',that.handleLeftClick)  
                    that.$cp.addTiles(shuibiaoUrl , item["matrix"])
                    break;
                case "华仪":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],dianbiao,'leftClick',that.handleLeftClick)  
                    that.$cp.addTiles(dianbiaoUrl , item["matrix"])
                    break;
                case "大华":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],yanwu,'leftClick',that.handleLeftClick)    
                    that.$cp.addTiles(yanwuUrl , item["matrix"])
                    break;
                case "德安":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],penlin,'leftClick',that.handleLeftClick)    
                    that.$cp.addTiles(penlinUrl , item["matrix"])
                    break;
                case "必达":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],menjin,'leftClick',that.handleLeftClick)  
                    that.$cp.addTiles(menjinUrl , item["matrix"])  
                    break;
                case "苏里":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],yinxiang,'leftClick',that.handleLeftClick)    
                    that.$cp.addTiles(yinxiangUrl , item["matrix"])  
                    break;
                case "米科":
                    that.$cp.addBillboard(item["设备编号"],item,[item["lon"],item["lat"],item["height"]],wendu,'leftClick',that.handleLeftClick)   
                    that.$cp.addTiles(wenduUrl , item["matrix"])  
                    break;
                } 
            })
        },
        addTiles(url){
            let tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
                url:url,
            }));
            tileset.readyPromise.then(function(tileset) {
                var heightOffset = 0;
                var boundingSphere = tileset.boundingSphere;
                var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
                var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
                var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
                var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
                tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
            }).otherwise(function(error) {
                throw (error);
            });
        },
        rotate() {
            var a = 0.1
            var t = Date.now()
            var n = (t - this.i) / 1e3
            this.i = t
            viewer.scene.camera.rotate(Cesium.Cartesian3.UNIT_Z, -a * n)
        },
        ...mapMutations("windowInfo", { changeTabName: "changeTabName" }),
        
        handleLeftClick(entity) {
            if(this.isBtn == 0){
                this.addBoundInfoBox(entity.position._value, "eq_detail");
                delete entity.info.height;
                delete entity.info.lon;
                delete entity.info.lat;
                delete entity.info.matrix;
                this.infoList = [];
                for(let key in entity.info){
                    this.infoList.push(key+": " + entity.info[key])
                }
            }else if(this.isBtn == 1){
                this.addBoundInfoBox(entity.position._value, "eq_detail");
                delete entity.info.height;
                delete entity.info.lon;
                delete entity.info.lat;
                delete entity.info.matrix;
                
                this.infoList = [];
                for(let key in entity.info){
                    this.infoList.push(key+": " + entity.info[key])
                }
            }else if(this.isBtn == 2){
                this.currentEntity = entity.info;
                this.activeName = "first"
                this.addBoundInfoBox(entity.position._value, "pop_nenghao");
                delete entity.info.height;
                delete entity.info.lon;
                delete entity.info.lat;
                delete entity.info.matrix;
                this.nenghaoList = [];
                for(let key in entity.info){
                    this.nenghaoList.push(key+": " + entity.info[key])
                }
                axios.get("./data/lonLat.json").then((res)=>{
                    let data = res.data.rows[0]["能耗监测"];
                    data.forEach(item=>{
                        if(item["监测设备编号"]===entity.info["设备编号"]){
                            console.log("asd")
                            this.tableData.push(
                                {
                                    num:item["监测设备编号"],
                                    time:item["监测时间"],
                                    type:item["能耗类型"],
                                    data:item["能耗数据"]
                                }
                            )
                        }
                    })
                    
                })

            }
            
            //this.infoList = this.infoList.slice(5)
        },

        addBoundInfoBox(positionValue, elementId) {
            const oneDiv = window.document.getElementById(elementId)
            oneDiv.style.display = 'block'
            this.preRenderListener = viewer.scene.preRender.addEventListener(function() {
                let elWidth = oneDiv.offsetWidth
                let elHeight = oneDiv.offsetHeight // + 60
                const scratch = new Cesium.Cartesian2() //cesium二维笛卡尔 笛卡尔二维坐标系就是我们熟知的而二维坐标系；三维也如此
                let domPosition = positionValue
                const canvasPosition = viewer.scene.cartesianToCanvasCoordinates(domPosition, scratch) //cartesianToCanvasCoordinates 笛卡尔坐标（3维度）到画布坐标
                if (Cesium.defined(canvasPosition)) {
                    // 根据元素宽高及当前点屏幕坐标进行偏移
                    oneDiv.style.top = canvasPosition.y - elHeight/10 + 'px'
                    //oneDiv.style.left = canvasPosition.x - elWidth / 2 + 'px'
                    oneDiv.style.left = canvasPosition.x  + 'px'
                }
            })
        },
        hiddenInfoBox(event) { 
            //Object.keys
            const oneDiv = window.document.getElementById("eq_detail")
            oneDiv.style.display = 'none'
        },
        hiddenPopBox(){
            const oneDiv = window.document.getElementById("pop_nenghao")
            oneDiv.style.display = 'none'
            this.activeName = "first"
        },
        //移除自定义信息框
        removeBoundInfoBox() {
            // if (oldBoundInfoBox) {
            // 	oldBoundInfoBox.style.display = 'none'
            // 	oldBoundInfoBox = null
            // }
            // 移除监听事件
            if (this.preRenderListener) {
                this.preRenderListener()
                this.preRenderListener = null
            }
        },
        drawNenghao(xData,yData) {
            let that = this;
            let myChart = this.$echarts.init(
                this.$refs.nenghaoChart
                //document.getElementById("nenghaoChart")
            );
            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        lineStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0,
                                    color: 'rgba(0, 255, 233,0)'
                                }, {
                                    offset: 0.5,
                                    color: 'rgba(255, 255, 255,1)',
                                }, {
                                    offset: 1,
                                    color: 'rgba(0, 255, 233,0)'
                                }],
                                global: false
                            }
                        },
                    },
                },
                grid: {
                    top: '5%',
                    left: '15%',
                    right: '15%',
                    bottom: '25%',
                    // containLabel: true
                },
                xAxis: [{
                    type: 'category',
                    axisLine: {
                        show: false
                    },
                    splitArea: {
                        // show: true,
                        color: '#f00',
                        lineStyle: {
                            color: '#f00'
                        },
                    },
                    axisLabel: {
                        color: '#fff'
                    },
                    splitLine: {
                        show: false
                    },
                    boundaryGap: false,
                    data: xData,

                }],

                yAxis: [{
                    type: 'value',
                    min: 0,
                    // max: 140,
                    splitNumber: 4,
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(255,255,255,0.1)'
                        }
                    },
                    axisLine: {
                        show: false,
                    },
                    axisLabel: {
                        show: true,
                        margin: 20,
                        textStyle: {
                            color: '#d1e6eb',

                        },
                    },
                    axisTick: {
                        show: false,
                    },
                }],
                series: [
                    {
                        name: '',
                        type: 'line',
                        smooth: false, //是否平滑
                        showAllSymbol: true,
                        // symbol: 'image://./static/images/guang-circle.png',
                        symbol: 'circle',
                        symbolSize: 10,
                        lineStyle: {
                            normal: {
                                color: "#00b3f4",
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                            
                            },
                        },
                        label: {
                            show: false,
                            position: 'top',
                            textStyle: {
                                color: '#00b3f4',
                            }
                        },
                        itemStyle: {
                            color: "#00b3f4",
                            borderColor: "#fff",
                            borderWidth: 1,
                            shadowColor: 'rgba(0, 0, 0, .3)',
                            shadowBlur: 0,
                            
                        },
                        tooltip: {
                            show: false
                        },
                        areaStyle: {
                            normal: {
                                color: new that.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                        offset: 0,
                                        color: 'rgba(0,179,244,0.3)'
                                    },
                                    {
                                        offset: 1,
                                        color: 'rgba(0,179,244,0)'
                                    }
                                ], false),
                                shadowColor: 'rgba(0,179,244, 1)',
                                shadowBlur: 20
                            }
                        },
                        data: yData
                    },
                ]
            };
            myChart.setOption(option);
            window.onresize = function () {
                myChart.resize();
            };
        },
        getXy(){
            var that = this;
            this.handler3D = new Cesium.ScreenSpaceEventHandler( viewer.scene.canvas);
                this.handler3D.setInputAction(function(movement) {
                var pick= new Cesium.Cartesian2(movement.position.x,movement.position.y);
                if(pick){
                    var cartesian =  viewer.scene.globe.pick( viewer.camera.getPickRay(pick),  viewer.scene);
                    if(cartesian){
                        //世界坐标转地理坐标（弧度）
                        var cartographic =  viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
                        if(cartographic){
                            //鼠标位置地球表面物体的真实海拔
                            var height = viewer.scene.globe.getHeight(cartographic);
                            //视角海拔高度
                            var he = Math.sqrt( viewer.scene.camera.positionWC.x *  viewer.scene.camera.positionWC.x +  viewer.scene.camera.positionWC.y *  viewer.scene.camera.positionWC.y +  viewer.scene.camera.positionWC.z *  viewer.scene.camera.positionWC.z);
                            var he2 = Math.sqrt(cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z);
                            //地理坐标（弧度）转经纬度坐标
                            var point=[ cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180];
                            if(!height){
                                height = 0;
                            }
                            let x = point[0].toFixed(6);  
                            let y = point[1].toFixed(6);
                            console.log(x+","+y)
                        }
                    }
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        },    
    }
}
</script>
<style lang="stylus">
    .EnergyConsumption .el-tabs__item{
        color:#fff;
    }
    .EnergyConsumption .el-table thead {
        color: #fff;
    }
    .EnergyConsumption .el-table--enable-row-hover .el-table__body tr:hover>td{
        background-color: #212e3e !important;
    }
    .EnergyConsumption .el-table{
        color: #fff;
    }
    .EnergyConsumption .el-table th,.EnergyConsumption .el-table tr {
        background-color: transparent;
    }
    .EnergyConsumption .el-table,.EnergyConsumption .el-table__expanded-cell {
        background-color: transparent;
    }
    #nenghaoChart{
        width:100%;
        height:300px;
    }
</style>
<style lang="stylus" scoped>
    @import '../../assets/css/varibles.styl'
    .buttons {
        position: fixed;
        left: 50%;
        transform: translateX(-50%);
        bottom: 2%;
        z-index: 9;
        display: flex;
        align-items: center;
    }
    .buttons .active{
        background: url("") no-repeat;
        background-size: 100% 100%;
    }
    .EquipmentDetails{
        background: rgba(0,0,0,.6);
        border-radius: .1rem;
        position: fixed;
        right: 3.6rem;
        top: 6.34rem;
        width: 3.6rem;
        height: 3.8rem;
        z-index: 2;
    }
    .EquipmentDetails:before {
        background: url("") no-repeat bottom;
        background-size: 100%;
        bottom: -2px;
    }
    .EquipmentDetails:after {
        background: url("") no-repeat;
        background-size: 100%;
        top: -2px;
    }
    .EquipmentDetails:after, .EquipmentDetails:before {
        content: "";
        width: calc(100% + .04rem);
        height: .2rem;
        position: absolute;
        left: -2px;
        pointer-events: none;
    }
    .EquipmentDetails .el-icon-close {
        position: absolute;
        top: .1rem;
        right: .1rem;
        font-size: .16rem;
        cursor: pointer;
    }
    .EquipmentDetails ul{
        width: 100%;
        height: 85%;
        font-size: .16rem;
        padding: 0 .2rem;
        overflow-y: auto;
        margin-top: .3rem;  
    }
    .EquipmentDetails ul li{
        line-height:.2rem
    }
    .EnergyConsumption{
        background: rgba(0,0,0,.6);
        border-radius: .1rem;
        width: 6rem;
        height: 5rem;
        z-index: 2;
    }
    .EnergyConsumption .el-tabs--card>.el-tabs__header .el-tabs__item.is-active {
        color: #fff;
        background: rgba(156,198,255,.3);
    }
    .EnergyConsumption .tabs-wrap{
        width: 100%;
        //height: 100%;
        font-size: .16rem;
        color:#fff;
        padding: .4rem .15rem;
    }
    .EnergyConsumption:before {
        background: url("") no-repeat bottom;
        background-size: 100%;
        bottom: -2px;
    }
    
    .EnergyConsumption:after {
        background: url("") no-repeat;
        background-size: 100%;
        top: -2px;
    }
    .EnergyConsumption:after, .EnergyConsumption:before {
        content: "";
        width: calc(100% + .04rem);
        height: .2rem;
        position: absolute;
        left: -2px;
        pointer-events: none;
    }
    .EnergyConsumption .el-icon-close {
        position: absolute;
        top: .1rem;
        right: .1rem;
        font-size: .16rem;
        cursor: pointer;
    }    
		
                
			
</style>